<?php

namespace common\core;

use Yii;
use yii\db\ActiveRecord;

class Debug extends ActiveRecord
{
    private $cacheKey = 'cache_debug_';

    public $data = array();

    function sTime($key)
    {
        list($t1, $t2) = explode(' ', microtime());
        $stime = (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);

        $cache = Yii::$app->cache;
        $cache->set($this->cacheKey . $key, $stime, 2 * 60);
    }

    function eTime($key)
    {
        $result = "出错了啦";

        list($t1, $t2) = explode(' ', microtime());
        $etime = (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);

        $cache = Yii::$app->cache;
        $stime = $cache->get($this->cacheKey . $key);
        if ($stime) {
            $result = (float)(($etime - $stime) / 1000);
        }

        $cache->delete($this->cacheKey . $key);
        $this->data[] = array("msg" => $key . '：' . $result . '秒');
        return $result;
    }

    function log($msg)
    {
        if (!empty($msg))
            $this->data[] = array("msg" => $msg);
    }

    function content()
    {
        $content = '';
        $isdebug = isset(yii::$app->params['debug']) ? yii::$app->params['debug'] : false;
        if ($isdebug) {
            $content = "<span style=' display: inline-block;z-index: 3000; position: fixed; left: 5px;bottom: 5px; min-height: 20px;line-height: 20px;padding:10px;font-size: 12px;color: #14ff10;background-color: #000; '>";
            $content .= "Debug Info";
            foreach ($this->data as $item) {
                $content .= '<br/>' . $item['msg'];
            }
            $content .= "</span>";
        }
        return $content;
    }
}
